<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of session
 *
 * @author rodrigo
 */
class SessionManager
{
    const SESSION_STARTED = TRUE;
    const SESSION_NOT_STARTED = FALSE;
	const SESSION_MAX_IDLE_TIME = 300;  // in seconds

    
    public static $sessionState;

	private $timeout_idle;

    // THE only instance of the class
    private static $instance;


    private function __construct() {}


    /**
    *    Returns THE instance of 'Session'.
    *    The session is automatically initialized if it wasn't.
    *
    *    @return    object
    **/

    public static function init(){
        self::$instance = new self;
        $_SESSION['logged'] = FALSE;
    }


	/**
    *    (Re)starts the session.
    *
    *    @return    bool    TRUE if the session has been initialized, else FALSE.
    **/

    public static function startSession()
    {

            session_start();
            $_SESSION['logged']=TRUE;
            SessionManager::setTimeOutSession();
            session_write_close();
        
    }

    public static function isLogged(){
        @session_start();
        $flag =SessionManager::checkTimeOut();
        if($flag) return false;
        if(isset ($_SESSION['logged'])){
            return $_SESSION['logged'];
        }else{
            return FALSE;
        }
        @session_write_close();
    }

    public static function putInSession($index,$value){
        @session_start();
        $_SESSION[$index] = $value;
        @session_write_close();
    }

    public static function getBySession($index){
        @session_start();
        @$return =  $_SESSION[$index];
        @session_write_close();
        return $return;
     }


    private static function setTimeOutSession() {

            $_SESSION['timeout_idle'] = time() + SessionManager::SESSION_MAX_IDLE_TIME;
    }

    public static function checkTimeOut()
    {
            if ( isset($_SESSION['timeout_idle'])) {
                    if ($_SESSION['timeout_idle'] < time()) {
                            SessionManager::destroy();
                            return true;
                    } else {
                            SessionManager::setTimeOutSession();
                            return false;
                    }
            } else {
                    SessionManager::setTimeOutSession();
                    return false;
            }
            return FALSE;
    }

    public static function destroy()
    {
        @session_start();
        @session_destroy();

    }
}
?>
